/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2019
 */

package com.jzwl.site.wap.wxUser.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.jzwl.common.cache.WeixinFactory;
import com.jzwl.common.constant.WeixinAccessTokenDto;
import com.jzwl.common.constant.WeixinUserInfoDto;
import com.jzwl.common.page.PageObject;
import com.jzwl.site.wap.wxUser.dao.WxUserDao;

@Service("wxUserService")
public class WxUserService {

	@Autowired
	private WxUserDao wxUserDao;

	public boolean addWxUser(Map<String, Object> map) {

		return wxUserDao.addWxUser(map);
	}

	public PageObject queryWxUserList(Map<String, Object> map) {

		return wxUserDao.queryWxUserList(map);

	}

	public boolean updateWxUser(Map<String, Object> map) {

		return wxUserDao.updateWxUser(map);

	}

	public boolean deleteWxUser(Map<String, Object> map) {

		return wxUserDao.deleteWxUser(map);

	}

	public Map<String, Object> queryUserInfoByOpenId(String openId) {

		return wxUserDao.queryUserInfoByOpenId(openId);

	}

	public WeixinUserInfoDto userInfo(String code) {

		WeixinAccessTokenDto weixinAccessTokenDto = WeixinFactory.fetchTokenFromWeixin(code);
		if (!"".equals(weixinAccessTokenDto.getOpenid())) {
			WeixinUserInfoDto userInfo = WeixinFactory.userInfo(weixinAccessTokenDto.getAccess_token(),
					weixinAccessTokenDto.getOpenid());
			Map<String, Object> map = wxUserDao.queryUserInfoByOpenId(weixinAccessTokenDto.getOpenid());
			if (null == map) {
				//获取用户存储
				Map<String, Object> userMap = Maps.newConcurrentMap();
				userMap.put("openId", userInfo.getOpenid());
				userMap.put("wxname", userInfo.getNickname());
				userMap.put("name", userInfo.getNickname());
				userMap.put("sex", userInfo.getSex());
				userMap.put("headImgUrl", userInfo.getHeadimgurl());
				addWxUser(userMap);

			}
			return userInfo;
		}

		return null;

	}
}
